/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.unice.miage.oobdoo.servlet;
import com.unice.miage.oobdoo.entity.Utilisateur;
import com.unice.miage.oobdoo.helpfull.LocalEncrypter;
import com.unice.miage.oobdoo.manager.UtilisateurManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Remi
 */
@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {

    @EJB
    private UtilisateurManager utilisateurManager;

    @Override
    public void init() throws ServletException {
        try {
            super.init();
            String path = this.getServletContext().getInitParameter("PATH");
            //String path =  System.getProperty("user.dir")+"/applications/oobdoo";
            utilisateurManager.setPATH(path);
            LocalEncrypter.setUp();
            utilisateurManager.creePremiersUtilisateurs();
        } catch (Exception ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");

        if (action != null) {
            if (action.equals("existLogin")) {
                String login = (String) request.getParameter("login");
                // VERIF SI LOGIN EXISTE
                boolean b;
                if (login != null) {
                    b = utilisateurManager.checkIfLoginExist(login);
                } else {
                    b = false;
                }

                //RENVOIE LA REPONSE EN JSON
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                if (b == true) {
                    out.println("{\"exist\":\"true\"}");
                } else {
                    out.println("{\"exist\":\"false\"}");
                }
            } else if (action.equals("allLogins"))
            {
                String q = (String) request.getParameter("q");
                if( q == null )
                {
                    return;
                }
                else
                {
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    Collection<Utilisateur> utilisateurs = utilisateurManager.getAllUsers();
                    for(Utilisateur u : utilisateurs)
                    {
                        String login = u.getLogin().toLowerCase();
                        String search = q.toLowerCase();
                        if( login.contains(search) )
                        {
                            String str = u.getLogin() + "\n";
                            out.println(str);
                        }
                    }
                }
            } else {
                String forwardTo = "";
                if (action.equals("connexion")) {
                    String login = (String) request.getParameter("login");
                    String pwd = (String) request.getParameter("pwd");

                    if (utilisateurManager.acceptConnexion(login, pwd)) {

                        Utilisateur u = utilisateurManager.getUtilisateurByLogin(login);
                        Date d = new Date();
                        utilisateurManager.updateLastLogin(u, d.getTime());
                        
                        forwardTo = "AlbumServlet?action=list";
                        HttpSession session = request.getSession(true);

                        // Session
                        session.setAttribute("login", u.getLogin());
                        session.setAttribute("email", u.getEmail());
                        session.setAttribute("id", u.getId());

                    } else {
                        forwardTo = "login.jsp?ec=error";
                    }
                } else if (action.equals("deconnexion")) {
                    HttpSession session = request.getSession(true);
                    //session.removeAttribute("login");
                    session.invalidate();
                    forwardTo = "index.jsp?";
                }
                RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                dp.forward(request, response);
            }
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
